package com.nl.controller.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.nl.controller.web.mapper.SmsUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.model.Response;
import com.nl.controller.common.util.ResponseUtil;
import com.nl.controller.web.bean.SmsMgrTemplateInfo;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.service.LoginService;
import com.nl.controller.web.service.SmsMgrTemplateInfoService;
import com.nl.controller.web.service.SmsUserService;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("mgrTemplate")
@Slf4j
public class SmsMgrTemplateInfoController {
	@Autowired
	private SmsMgrTemplateInfoService smsMgrTemplateInfoService;
	@Autowired
	private LoginService loginService;
	@Autowired
	private SmsUserService smsUserService;


	@Autowired
	private SmsUserMapper smsUserMapper;


	SmsMgrTemplateInfo tempMgrTemplateInfo;

    @ApiOperation(value = "查询项目模板表", notes = "查询项目模板表")
    @PostMapping("find")
    public Response find(@RequestParam(value = "page", required = true) int page,
            @RequestParam(value = "limit", required = true) int limit,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "countyId", required = false) String countyId,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "mgrName", required = false) String mgrName,
            @RequestParam(value = "mgrState", required = false) String mgrState,
            @RequestParam(value = "templateState", required = false) String templateState,
            @RequestParam(value = "flag", required = false) String flag,
            @RequestParam(value = "duty", required = false) String duty,
            @RequestParam Map<String, Object> paramMap,HttpSession session) {
            SmsUsers user = (SmsUsers) session.getAttribute("user");
            //duty = user.getDuty();
            String msisdn = user.getMsisdn();
            if ("".equals(duty) || duty == null) {
                throw new SmsException("请选择查询条件，开始查询");
            } else {
            	 PageInfo<SmsMgrTemplateInfo> pageInfo = smsMgrTemplateInfoService.find(page, limit, cityId, countyId, mgrId,mgrName, mgrState, templateState, flag,duty,msisdn);
                 log.info(" 查询模板信息：{}", paramMap.toString());
                 log.debug("查询模板信息返回参数：{}", pageInfo.getList().toString());
                 return ResponseUtil.sucess(pageInfo.getList(), pageInfo.getTotal());
			}
    }
    @ApiOperation(value = "通过项目id查询项目模板表", notes = "通过项目id查询项目模板表")
    @PostMapping("findMgrTemplateByMgrId")
    public Response findMgrTemplateByMgrId(
            @RequestParam(value = "mgrId", required = false) String mgrId) {
        SmsMgrTemplateInfo smsMgrTemplateInfo;
        smsMgrTemplateInfo = smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId);
        tempMgrTemplateInfo=smsMgrTemplateInfo;
        log.info(" 项目信息：{}", smsMgrTemplateInfo.toString());
        return ResponseUtil.sucess(smsMgrTemplateInfo);
    }
	@ApiOperation(value = "插入项目模板表", notes = "插入项目模板表")
	@PostMapping("configureMgrTemplate")
	public Response configureMgrTemplate(
			@RequestParam(value = "cityId", required = false) String cityId,
			@RequestParam(value = "countyId", required = false) String countyId,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "extId", required = false) String extId,
			@RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime", required = false) String endTime,
			@RequestParam(value = "isLocal", required = false) String isLocal,
			@RequestParam(value = "threshold", required = false) int threshold,
			@RequestParam(value = "isThreshold", required = false) String isThreshold,
			@RequestParam(value = "content", required = false) String content,
			@RequestParam(value = "tabindex", required = false) String tabindex,
			@RequestParam(value = "mgrId", required = false) String mgrId,
			@RequestParam(value = "regionId", required = false) String regionId,
			@RequestParam(value = "regionType", required = false) String regionType,
			@RequestParam(value = "regionTypeValue", required = false) String regionTypeValue,
			@RequestParam(value = "reset", required = false) String reset,
			@RequestParam(value = "flag", required = false) String flag,
			@RequestParam(value = "cycle", required = false) String cycle,
			@RequestParam(value = "cycleThreshold", required = false) String cycleThreshold,
			@RequestParam(value = "localDate", required = false) String localDate,
			@RequestParam(value = "mgrFlag", required = false) String mgrFlag,
			HttpSession session, @RequestParam Map<String, Object> paramMap) {
		log.info("插入项目模板参数：{}", paramMap.toString());
		SmsUsers user = (SmsUsers) session.getAttribute("user");
		String cityName = smsMgrTemplateInfoService.findCityName(cityId);
		String mgrState = "";
		String templateState = "";

		log.info(startTime+endTime);
//		if (user.getDuty().equals("0")) {
//			mgrState = "0";
//			templateState="2";
//		}
		int checkNum = 0;
		int result = 0;
		//参数处理
		log.info("根据城市查询扩展码信息参数：{}", cityId);
		List<String> list = new ArrayList<>();
		if (cityId != null && !"undefined".equals(cityId) && cityId != "") {
			list = smsUserService.findExtIdByCityId(cityId);
		}
		SmsMgrTemplateInfo smsMgrTemplateInfo;
		if ("modify".equals(flag)) {
			smsMgrTemplateInfo = smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId);
			checkNum = Integer.parseUnsignedInt(smsMgrTemplateInfo.getCheckNum())+1;
			tempMgrTemplateInfo=smsMgrTemplateInfo;
			if(!content.equals(tempMgrTemplateInfo.getContent())){
				mgrState = "3";//配置中
				templateState = "0";//待审核
			}else{
				//不改变状态
				mgrState = smsMgrTemplateInfo.getMgrState();
				templateState = smsMgrTemplateInfo.getTemplateState();
			}
		}else{
			mgrState = "3";//配置中
			templateState = "0";//待审核
		}
		extId = list.get(0);
		log.debug("根据城市查询扩展码信息返回数据：{}", list.size());
		result = smsMgrTemplateInfoService.configureMgrTemplate(cityId,countyId,name,extId,startTime,endTime,isLocal,
				threshold,isThreshold,content,tabindex,mgrId,regionId,regionType,regionTypeValue,mgrState,templateState,flag,
				user.getMsisdn(),cycle,cycleThreshold,localDate,checkNum,mgrFlag);
		log.debug("插入项目模板表返回参数：{}", result);
		if (result == 1) {
			StringBuffer sbf = new StringBuffer();
			//String contents = "【江苏省应急平台】"+cityName+"项目：" + smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId).getName()+"，项目编码为:"+mgrId+"+"+checkNum+ "已完成配置，请审核，";
			String contents = "【江苏省应急平台】您好，"+cityName+"项目：" + smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId).getName()+"，项目编码为:"+mgrId+"，已完成配置，请审核，";
			sbf.append(contents);
			if ("modify".equals(flag) && !user.getDuty().equals("0")) {

				if (!(content).equals(tempMgrTemplateInfo.getContent())) {
					//sbf.append("改动项:");
					sbf.append("短信内容改为 :"+content+",原先为 :"+tempMgrTemplateInfo.getContent());
					sbf.append("，审核通过请回复\'Y-"+mgrId+"+"+checkNum+"-YJ\'");
					sbf.append("，审核不通过请回复\'N-"+mgrId+"+"+checkNum+"-YJ\'。");
					List<SmsUsers> smsUsers = smsUserService.findCityUsersbyCityId(cityId);
					if (null!= smsUsers && !smsUsers.isEmpty()) {
						for (SmsUsers smsUser : smsUsers) {
							loginService.sendCode(smsUser.getMsisdn(),sbf.toString());
							log.info("手机号" + smsUser.getMsisdn());
							log.info(sbf.toString());
						}
					}
				}
			}else if ("insert".equals(flag) ) {
				int checkNumber = checkNum +1;
				sbf.append("该项目为应急平台新建项目,短信内容 :"+content);
				sbf.append("，审核通过请回复\'Y-"+mgrId+"+"+checkNumber+"-YJ\'");
				sbf.append("，审核不通过请回复\'N-"+mgrId+"+"+checkNumber+"-YJ\'。");
				List<SmsUsers> smsUsers = smsUserService.findCityUsersbyCityId(cityId);
				if (null!= smsUsers && !smsUsers.isEmpty()) {
					for (SmsUsers smsUser : smsUsers) {
						loginService.sendCode(smsUser.getMsisdn(),sbf.toString());
						log.info("手机号" + smsUser.getMsisdn());
						log.info(sbf.toString());
					}
				}
			}else if ("xuYiInsert".equals(flag)){
				//自定义短信内容，发送审核短信
				if("0".equals(tabindex)){
					int checkNumber = checkNum +1;
					sbf.append("该项目为盱眙供电局新建项目,短信内容 :"+content);
					sbf.append("，审核通过请回复\'Y-"+mgrId+"+"+checkNumber+"-XYGD\'");
					sbf.append("，审核不通过请回复\'N-"+mgrId+"+"+checkNumber+"-XYGD\'。");
					List<SmsUsers> smsUsers = smsUserService.findCityUsersbyCityId(cityId);
					if (null!= smsUsers && !smsUsers.isEmpty()) {
						for (SmsUsers smsUser : smsUsers) {
							loginService.sendCode(smsUser.getMsisdn(),sbf.toString());
							log.info("手机号" + smsUser.getMsisdn());
							log.info(sbf.toString());
						}
					}
				}else{
				//使用短信模板，无需发送审核短信，通知系统管理员即可。
					String content2 = "【江苏省应急平台】您好，"+cityName+"项目：" + smsMgrTemplateInfoService.findMgrTemplateByMgrId(mgrId).getName()+"，项目编码为:"+mgrId+"，由"+user.getMsisdn()+"创建，项目短信内容为："+content+",该项目使用供电局短信模板，无需审核，请悉知。";
					//审核通过，通知系统管理员
					Map<String, Object> map2 = new HashMap<String, Object>();
					map2.put("duty", "0");
					List<SmsUsers> provinceUsers = smsUserMapper.findUser(map2);
					for (SmsUsers smsUsers : provinceUsers) {
						loginService.sendCode(smsUsers.getMsisdn(),content2);
					}
				}

			}

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("mgrId", mgrId);
			map.put("reset", reset);
			smsMgrTemplateInfoService.resetThreshold(map);
			return ResponseUtil.sucess("配置成功");
		} else {
			log.debug("插入项目模板表返回参数：{}", result);
			return ResponseUtil.error(result, "插入项目模板表失败，请重试");
		}
	}
		@ApiOperation(value = "修改项目状态", notes = "修改项目状态")
		@PostMapping("modifyMgrState")
		private Response modifyMgrState(
				@RequestParam(value = "id") String id,
				@RequestParam(value ="cityId",required =false) String cityId,
				@RequestParam(value ="mgrState",required =false) String mgrState,
				@RequestParam(value ="templateState",required =false) String templateState,
				@RequestParam Map<String, Object> paramMap) {
			int result = smsMgrTemplateInfoService.modifyMgrState(id, cityId, mgrState,templateState);
			if(result>0){
				log.info("修改项目状态信息:{}" ,paramMap.toString());
				log.info("修改项目状态信息返回参数：",result);
				return ResponseUtil.sucess("success");
			} else {
				log.error("修改项目状态信息返回参数：{}", result);
				return ResponseUtil.error(-1, "修改项目状态失败，请重试");
			}

		}
	}

